package com.example.nonggo.presenter;

import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import com.example.nonggo.base.BasePresenter;
import com.example.nonggo.contract.QuestionContract;
import com.example.nonggo.model.QuestionModel;
import com.example.nonggo.utils.CustomToastUtils;

import java.io.File;

public class QuestionPresenter extends BasePresenter<QuestionContract> implements QuestionContract.Presenter {
    private final QuestionModel questionModel;
    private static final String TAG = "QuestionPresenter";

    private volatile MediaRecorder mRecorder;
    private boolean isRecording = false;
    private File audioFile;

    private Handler handler;
    private Runnable updateWaveformRunnable;
    long startRecordTime = 0;
    public QuestionPresenter(QuestionModel questionModel) {
        this.questionModel = questionModel;
        this.questionModel.registerCallBack(this);
        // 初始化 Handler
        handler = new Handler();
        // 初始化 Runnable
        updateWaveformRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isRecording || mRecorder == null) {
                    return;
                }
               try {
                   int maxAmplitude = mRecorder.getMaxAmplitude();
                   int db = maxAmplitude / 35;
                   Log.i(TAG, "分贝:" + db);
                   db = Math.min(200, db);
                   // 更新波形
                   getView().updateWaveform(db);
                   handler.postDelayed(this, 250); // 每 250 毫秒更新一次
               } catch (Exception e) {

               }
            }
        };
    }

    @Override
    public void destroy() {
        super.destroy();
        handler = null;
        updateWaveformRunnable = null;
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
    }

    public void getVerCode(String query, String area, String user) {
        questionModel.getWearChatMessages(query, area, user);
    }

    @Override
    public void wearChatMessages(String data) {
        if (data != null && getView() != null) {
            getView().getQuestion(data);
        }
    }

    @Override
    public void translateText(String s) {
        getView().hideLoading();
        if (s == null || s.isEmpty()) {
            CustomToastUtils.showCustomToast("未识别到内容");
        }
        // 语音转文本后续处理
        if (s != null && getView() != null) {
            getView().addNewQuestion(s);
            getView().hideLoading();
        }
    }

    /**
     * 开始录音
     */
    public void startRecording() {
        audioFile = new File(getView().getFilesDir() + "/" + "voice_" + System.currentTimeMillis() + ".wav");
        try {
            if (mRecorder != null) {
                mRecorder.reset();
            } else {
                mRecorder = new MediaRecorder();
            }
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(16000);
            startRecordTime= System.currentTimeMillis();

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mRecorder.setOutputFile(audioFile);
                }
                mRecorder.prepare();
                mRecorder.start();
            } catch (Exception e) {
                mRecorder.release();
                mRecorder = null;
//                toast("录音失败");
                return;
            }
            isRecording = true;
            getView().showMicMask();
            handler.post(updateWaveformRunnable); // 启动 Runnable
        } catch (Exception e) {
            Log.d(TAG, "startRecording: ");
        }

    }

    /**
     * 结束录音并转录
     */
    public void stopRecordingAndTranscribe() {
        getView().hideMicMask();
        getView().showLoading();
        if (mRecorder != null) {
            isRecording = false;
            mRecorder.stop();//停止时没有prepare，就会报stop failed
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            handler.removeCallbacks(updateWaveformRunnable);
            // 录音小于2秒则不进行识别
            if (System.currentTimeMillis() - startRecordTime < 2000) {
                CustomToastUtils.showCustomToast("录音时间太短");
                return;
            }
            // 调用语音转文字的API
            getView().showLoading();
            questionModel.fileTranslateText(audioFile.getAbsolutePath());
        }
    }
}
